import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "../components" as Components
import "../styles" as Styles

Dialog {
    id: manualControlDialog
    title: qsTr("手动控制 - %1").arg(agv ? agv.id : "")
    modal: true
    standardButtons: Dialog.Close

    // 自定义属性
    property var agv: null
    property bool isControlling: false
    property real currentSpeed: 0.5
    property real currentRotationSpeed: 0.3

    // 信号
    signal commandsAccepted(var commands)
    signal controlCancelled()

    width: 600
    height: 700

    onRejected: {
        stopAllControls()
        manualControlDialog.controlCancelled()
    }

    onClosed: {
        stopAllControls()
    }

    contentItem: Rectangle {
        color: Styles.Theme.background
        radius: Styles.Theme.radiusNormal

        ColumnLayout {
            anchors.fill: parent
            anchors.margins: Styles.Theme.spacingLarge
            spacing: Styles.Theme.spacingNormal

            // 警告区域
            Pane {
                Layout.fillWidth: true
                padding: Styles.Theme.spacingNormal
                background: Rectangle {
                    color: Styles.Theme.warning
                    opacity: 0.1
                    border.color: Styles.Theme.warning
                    border.width: 1
                    radius: Styles.Theme.radiusSmall
                }

                contentItem: ColumnLayout {
                    spacing: Styles.Theme.spacingSmall

                    RowLayout {
                        Layout.fillWidth: true

                        Text {
                            text: "⚠️"
                            font.pixelSize: Styles.Theme.fontSizeLarge
                            color: Styles.Theme.warning
                        }

                        Text {
                            Layout.fillWidth: true
                            text: qsTr("手动控制模式")
                            color: Styles.Theme.warning
                            font.pixelSize: Styles.Theme.fontSizeNormal
                            font.weight: Styles.Theme.fontWeightMedium
                        }
                    }

                    Text {
                        Layout.fillWidth: true
                        text: qsTr("警告: 在手动控制模式下，AGV将脱离自动调度系统。请确保周围环境安全，随时准备使用急停按钮。操作人员需要承担安全责任。")
                        color: Styles.Theme.warning
                        font.pixelSize: Styles.Theme.fontSizeSmall
                        wrapMode: Text.WordWrap
                    }
                }
            }

            // AGV状态区域
            Pane {
                Layout.fillWidth: true
                padding: Styles.Theme.spacingNormal
                background: Rectangle {
                    color: Styles.Theme.surface
                    border.color: Styles.Theme.border
                    border.width: 1
                    radius: Styles.Theme.radiusSmall
                }

                contentItem: ColumnLayout {
                    spacing: Styles.Theme.spacingSmall

                    Text {
                        text: qsTr("AGV状态")
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeNormal
                        font.weight: Styles.Theme.fontWeightMedium
                    }

                    GridLayout {
                        Layout.fillWidth: true
                        columns: 4
                        rowSpacing: Styles.Theme.spacingSmall
                        columnSpacing: Styles.Theme.spacingNormal

                        Text {
                            text: qsTr("状态:")
                            color: Styles.Theme.textSecondary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                        }

                        Rectangle {
                            Layout.preferredWidth: 80
                            Layout.preferredHeight: 20
                            radius: 10
                            color: getAgvStatusColor(agv ? agv.status : "")

                            Text {
                                anchors.centerIn: parent
                                text: getAgvStatusText(agv ? agv.status : "")
                                color: Styles.Theme.textOnPrimary
                                font.pixelSize: 10
                            }
                        }

                        Text {
                            text: qsTr("电量:")
                            color: Styles.Theme.textSecondary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                        }

                        Text {
                            text: agv ? qsTr("%1%").arg(Math.round(agv.battery || 0)) : ""
                            color: getBatteryTextColor(agv ? agv.battery : 0)
                            font.pixelSize: Styles.Theme.fontSizeSmall
                            font.weight: Styles.Theme.fontWeightMedium
                        }

                        Text {
                            text: qsTr("位置:")
                            color: Styles.Theme.textSecondary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                        }

                        Text {
                            text: formatPosition(agv ? agv.x : null, agv ? agv.y : null)
                            color: Styles.Theme.textPrimary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                        }

                        Text {
                            text: qsTr("速度:")
                            color: Styles.Theme.textSecondary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                        }

                        Text {
                            text: agv ? qsTr("%1 m/s").arg((agv.speed || 0).toFixed(2)) : ""
                            color: Styles.Theme.textPrimary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                        }
                    }
                }
            }

            // 控制面板区域
            Rectangle {
                Layout.fillWidth: true
                Layout.fillHeight: true
                color: Styles.Theme.surface
                border.color: Styles.Theme.border
                border.width: 1
                radius: Styles.Theme.radiusSmall

                ColumnLayout {
                    anchors.fill: parent
                    anchors.margins: Styles.Theme.spacingNormal
                    spacing: Styles.Theme.spacingNormal

                    Text {
                        text: qsTr("控制面板")
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeNormal
                        font.weight: Styles.Theme.fontWeightMedium
                    }

                    RowLayout {
                        Layout.fillWidth: true
                        spacing: Styles.Theme.spacingLarge

                        // 左侧 - 方向控制
                        ColumnLayout {
                            Layout.fillWidth: true
                            spacing: Styles.Theme.spacingNormal

                            Text {
                                text: qsTr("方向控制")
                                color: Styles.Theme.textSecondary
                                font.pixelSize: Styles.Theme.fontSizeSmall
                                font.weight: Styles.Theme.fontWeightMedium
                            }

                            // 方向控制按钮
                            GridLayout {
                                Layout.alignment: Qt.AlignHCenter
                                columns: 3
                                rowSpacing: Styles.Theme.spacingSmall
                                columnSpacing: Styles.Theme.spacingSmall

                                Item { width: 50; height: 50 }

                                Components.ActionButton {
                                    Layout.preferredWidth: 50
                                    Layout.preferredHeight: 50
                                    text: "▲"
                                    buttonType: "primary"
                                    enabled: agv && agv.status !== "offline"
                                    onButtonPressed: startMovement("forward")
                                    onButtonReleased: stopMovement()
                                }

                                Item { width: 50; height: 50 }

                                Components.ActionButton {
                                    Layout.preferredWidth: 50
                                    Layout.preferredHeight: 50
                                    text: "◀"
                                    buttonType: "primary"
                                    enabled: agv && agv.status !== "offline"
                                    onButtonPressed: startMovement("left")
                                    onButtonReleased: stopMovement()
                                }

                                Components.ActionButton {
                                    Layout.preferredWidth: 50
                                    Layout.preferredHeight: 50
                                    text: "⏹"
                                    buttonType: "danger"
                                    enabled: agv && agv.status !== "offline"
                                    onClicked: emergencyStop()
                                }

                                Components.ActionButton {
                                    Layout.preferredWidth: 50
                                    Layout.preferredHeight: 50
                                    text: "▶"
                                    buttonType: "primary"
                                    enabled: agv && agv.status !== "offline"
                                    onButtonPressed: startMovement("right")
                                    onButtonReleased: stopMovement()
                                }

                                Item { width: 50; height: 50 }

                                Components.ActionButton {
                                    Layout.preferredWidth: 50
                                    Layout.preferredHeight: 50
                                    text: "▼"
                                    buttonType: "primary"
                                    enabled: agv && agv.status !== "offline"
                                    onButtonPressed: startMovement("backward")
                                    onButtonReleased: stopMovement()
                                }

                                Item { width: 50; height: 50 }
                            }

                            // 旋转控制
                            RowLayout {
                                Layout.fillWidth: true

                                Components.ActionButton {
                                    Layout.fillWidth: true
                                    text: qsTr("左转")
                                    iconSource: "↺"
                                    buttonType: "secondary"
                                    enabled: agv && agv.status !== "offline"
                                    onButtonPressed: startRotation("left")
                                    onButtonReleased: stopMovement()
                                }

                                Components.ActionButton {
                                    Layout.fillWidth: true
                                    text: qsTr("右转")
                                    iconSource: "↻"
                                    buttonType: "secondary"
                                    enabled: agv && agv.status !== "offline"
                                    onButtonPressed: startRotation("right")
                                    onButtonReleased: stopMovement()
                                }
                            }
                        }

                        // 右侧 - 参数控制
                        ColumnLayout {
                            Layout.fillWidth: true
                            spacing: Styles.Theme.spacingNormal

                            Text {
                                text: qsTr("参数设置")
                                color: Styles.Theme.textSecondary
                                font.pixelSize: Styles.Theme.fontSizeSmall
                                font.weight: Styles.Theme.fontWeightMedium
                            }

                            // 移动速度
                            ColumnLayout {
                                Layout.fillWidth: true
                                spacing: Styles.Theme.spacingSmall

                                RowLayout {
                                    Layout.fillWidth: true

                                    Text {
                                        text: qsTr("移动速度:")
                                        color: Styles.Theme.textSecondary
                                        font.pixelSize: Styles.Theme.fontSizeSmall
                                        Layout.preferredWidth: 80
                                    }

                                    Text {
                                        text: qsTr("%1 m/s").arg(speedSlider.value.toFixed(1))
                                        color: Styles.Theme.textPrimary
                                        font.pixelSize: Styles.Theme.fontSizeSmall
                                        font.weight: Styles.Theme.fontWeightMedium
                                        Layout.fillWidth: true
                                    }
                                }

                                Slider {
                                    id: speedSlider
                                    Layout.fillWidth: true
                                    from: 0.1
                                    to: 2.0
                                    value: currentSpeed
                                    stepSize: 0.1
                                    onValueChanged: currentSpeed = value
                                }
                            }

                            // 旋转速度
                            ColumnLayout {
                                Layout.fillWidth: true
                                spacing: Styles.Theme.spacingSmall

                                RowLayout {
                                    Layout.fillWidth: true

                                    Text {
                                        text: qsTr("旋转速度:")
                                        color: Styles.Theme.textSecondary
                                        font.pixelSize: Styles.Theme.fontSizeSmall
                                        Layout.preferredWidth: 80
                                    }

                                    Text {
                                        text: qsTr("%1 rad/s").arg(rotationSlider.value.toFixed(1))
                                        color: Styles.Theme.textPrimary
                                        font.pixelSize: Styles.Theme.fontSizeSmall
                                        font.weight: Styles.Theme.fontWeightMedium
                                        Layout.fillWidth: true
                                    }
                                }

                                Slider {
                                    id: rotationSlider
                                    Layout.fillWidth: true
                                    from: 0.1
                                    to: 1.0
                                    value: currentRotationSpeed
                                    stepSize: 0.1
                                    onValueChanged: currentRotationSpeed = value
                                }
                            }

                            // 控制选项
                            ColumnLayout {
                                Layout.fillWidth: true
                                spacing: Styles.Theme.spacingSmall

                                Text {
                                    text: qsTr("控制选项:")
                                    color: Styles.Theme.textSecondary
                                    font.pixelSize: Styles.Theme.fontSizeSmall
                                }

                                CheckBox {
                                    id: smoothControlCheck
                                    text: qsTr("平滑控制")
                                    checked: true
                                }

                                CheckBox {
                                    id: precisionModeCheck
                                    text: qsTr("精确模式")
                                    checked: false
                                    onToggled: {
                                        if (checked) {
                                            speedSlider.to = 0.5
                                            rotationSlider.to = 0.3
                                        } else {
                                            speedSlider.to = 2.0
                                            rotationSlider.to = 1.0
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // 快捷操作区域
                    Pane {
                        Layout.fillWidth: true
                        padding: Styles.Theme.spacingNormal
                        background: Rectangle {
                            color: Styles.Theme.backgroundSecondary
                            border.color: Styles.Theme.border
                            border.width: 1
                            radius: Styles.Theme.radiusSmall
                        }

                        contentItem: ColumnLayout {
                            id: quickActionsColumn
                            spacing: Styles.Theme.spacingSmall

                            Text {
                                text: qsTr("快捷操作")
                                color: Styles.Theme.textPrimary
                                font.pixelSize: Styles.Theme.fontSizeSmall
                                font.weight: Styles.Theme.fontWeightMedium
                            }

                            GridLayout {
                                Layout.fillWidth: true
                                columns: 3
                                columnSpacing: Styles.Theme.spacingSmall
                                rowSpacing: Styles.Theme.spacingSmall

                                Components.ActionButton {
                                    Layout.fillWidth: true
                                    text: qsTr("前进1米")
                                    buttonType: "secondary"
                                    enabled: agv && agv.status !== "offline"
                                    onClicked: executeCommand("move_distance", { distance: 1.0, direction: "forward" })
                                }

                                Components.ActionButton {
                                    Layout.fillWidth: true
                                    text: qsTr("后退1米")
                                    buttonType: "secondary"
                                    enabled: agv && agv.status !== "offline"
                                    onClicked: executeCommand("move_distance", { distance: 1.0, direction: "backward" })
                                }

                                Components.ActionButton {
                                    Layout.fillWidth: true
                                    text: qsTr("原地360°")
                                    buttonType: "secondary"
                                    enabled: agv && agv.status !== "offline"
                                    onClicked: executeCommand("rotate_angle", { angle: 360 })
                                }

                                Components.ActionButton {
                                    Layout.fillWidth: true
                                    text: qsTr("左转90°")
                                    buttonType: "secondary"
                                    enabled: agv && agv.status !== "offline"
                                    onClicked: executeCommand("rotate_angle", { angle: -90 })
                                }

                                Components.ActionButton {
                                    Layout.fillWidth: true
                                    text: qsTr("右转90°")
                                    buttonType: "secondary"
                                    enabled: agv && agv.status !== "offline"
                                    onClicked: executeCommand("rotate_angle", { angle: 90 })
                                }

                                Components.ActionButton {
                                    Layout.fillWidth: true
                                    text: qsTr("停止所有")
                                    buttonType: "danger"
                                    enabled: agv && agv.status !== "offline"
                                    onClicked: stopAllControls()
                                }
                            }
                        }
                    }

                    // 状态显示
                    Rectangle {
                        Layout.fillWidth: true
                        Layout.preferredHeight: 30
                        color: isControlling ? Styles.Theme.info : Styles.Theme.backgroundSecondary
                        opacity: 0.1
                        border.color: isControlling ? Styles.Theme.info : Styles.Theme.border
                        border.width: 1
                        radius: Styles.Theme.radiusSmall

                        Text {
                            anchors.centerIn: parent
                            text: isControlling ? qsTr("正在控制AGV...") : qsTr("等待控制指令")
                            color: isControlling ? Styles.Theme.info : Styles.Theme.textSecondary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                            font.weight: Styles.Theme.fontWeightMedium
                        }
                    }
                }
            }
        }
    }

    footer: DialogButtonBox {
        standardButtons: Dialog.Close

        Component.onCompleted: {
            standardButton(Dialog.Close).text = qsTr("关闭")
        }
    }

    // 控制定时器
    Timer {
        id: controlTimer
        interval: 100
        repeat: true
        running: isControlling
        onTriggered: {
            // 持续发送控制指令
            sendControlCommand()
        }
    }

    // 当前控制状态
    property string currentAction: ""
    property var currentParameters: ({})

    // 辅助函数
    function getAgvStatusColor(status) {
        switch(status) {
            case "idle": return Styles.Theme.success
            case "executing": return Styles.Theme.info
            case "charging": return Styles.Theme.warning
            case "error": return Styles.Theme.danger
            case "offline": return Styles.Theme.textSecondary
            default: return Styles.Theme.textSecondary
        }
    }

    function getAgvStatusText(status) {
        switch(status) {
            case "idle": return qsTr("空闲")
            case "executing": return qsTr("执行中")
            case "charging": return qsTr("充电中")
            case "error": return qsTr("故障")
            case "offline": return qsTr("离线")
            default: return qsTr("未知")
        }
    }

    function getBatteryTextColor(battery) {
        var level = battery || 0
        if (level > 50) return Styles.Theme.success
        if (level > 20) return Styles.Theme.warning
        return Styles.Theme.danger
    }

    function formatPosition(x, y) {
        if (x == null || y == null || x === undefined || y === undefined) return qsTr("未知位置")
        return qsTr("(%1, %2)").arg(x.toFixed(1)).arg(y.toFixed(1))
    }

    function startMovement(direction) {
        currentAction = "move"
        currentParameters = {
            direction: direction,
            speed: currentSpeed,
            smooth: smoothControlCheck.checked,
            precision: precisionModeCheck.checked
        }
        isControlling = true
        console.log("Start movement:", direction, "speed:", currentSpeed)
    }

    function startRotation(direction) {
        currentAction = "rotate"
        currentParameters = {
            direction: direction,
            speed: currentRotationSpeed,
            smooth: smoothControlCheck.checked,
            precision: precisionModeCheck.checked
        }
        isControlling = true
        console.log("Start rotation:", direction, "speed:", currentRotationSpeed)
    }

    function stopMovement() {
        currentAction = "stop"
        currentParameters = {}
        isControlling = false
        console.log("Stop movement")
        sendControlCommand()
    }

    function emergencyStop() {
        currentAction = "emergency_stop"
        currentParameters = {}
        isControlling = false
        console.log("Emergency stop")
        sendControlCommand()
    }

    function stopAllControls() {
        isControlling = false
        currentAction = "stop_all"
        currentParameters = {}
        sendControlCommand()
        console.log("Stop all controls")
    }

    function executeCommand(action, parameters) {
        var command = {
            action: action,
            parameters: parameters || {},
            timestamp: Date.now()
        }
        console.log("Execute command:", JSON.stringify(command))
        // TODO: 发送到后端执行
    }

    function sendControlCommand() {
        if (!agv || agv.status === "offline") return

        var command = {
            action: currentAction,
            parameters: currentParameters,
            timestamp: Date.now()
        }

        console.log("Send control command:", JSON.stringify(command))
        // TODO: 通过WebSocket或其他方式发送到AGV控制器
    }

    onOpened: {
        forceActiveFocus()
        isControlling = false
        currentAction = ""
        currentParameters = {}
    }
}